import React from 'react';
import { Form, Tooltip } from 'antd';
import classNames from 'classnames';
import { useLanguage } from '@deepfos/store';
import { usePersistFn } from 'ahooks';
import type { ColumnsType, TablePaginationConfig } from 'antd/lib/table';
import type { FilterValue } from 'antd/es/table/interface';
import { uniqueId, findLastIndex } from 'lodash';
import type { DataListItemFieldType } from '@/services/listTable';
import styles from './TablePart.module.less';
import { formatTableShowData, getTableLineHeight } from '../utils/tableUtils';
import type { ComponentsProp } from '../utils/types';
import VirtualStickyTable from '@/components/virtual-sticky-table';
import { getGapByLayout } from '../utils/handlePovData';
import ViewTableCell from './view/ViewTableCell';

interface FormListTableProps extends ComponentsProp {
  size: { width: number; height: number };
  tableChange: (
    p: TablePaginationConfig,
    _f: Record<string, FilterValue | null>,
    s: Record<string, any> | Record<string, any>[],
  ) => void;
  pagination?: TablePaginationConfig;
  povHeightInfo?: {
    height: number;
    expand: boolean;
  };
  loading: boolean;
  lineHeight: number;
}

interface MemberLabelColorProps {
  code?: string;
  color?: string;
}

const lineHeightVal = {
  1: 32,
  2: 40,
  3: 48,
};

/**
 * 电子清单使用视图-渲染table区域
 *
 */
const FormListTable = ({
  size,
  tableChange,
  pagination,
  state,
  tableForm: form,
  query,
  povHeightInfo,
  loading,
  lineHeight = 1,
}: FormListTableProps) => {
  const locale = useLanguage().currentLanguage;
  const fixedClassName = `fixed-item_${query.elementName}${query.now || ''}`;
  const { listConfigData, styleObj } = state;

  const showColumn = React.useMemo(() => {
    return (listConfigData?.columnList || []).filter(
      (item) => item.cookiesActive && item.isHide === 0,
    );
  }, [listConfigData]);

  // 列宽计算规则，有责去配置信息中的，无责默认最小150px
  const noWidthColLength = showColumn.filter((item) => !item.customColumnWidth)?.length || 0;
  // 获取所有配置的列宽
  const totalColWidth = showColumn?.reduce((x, colItem) => {
    return x + (colItem.customColumnWidth || 150);
  }, 0);

  const windowWidth = React.useMemo(() => window.innerWidth, []);
  function getColumnWidth(colWidth: number, index: number) {
    // table宽度超过屏幕可视区域
    if (windowWidth <= totalColWidth) {
      return colWidth || 150;
    }
    const averageVal = noWidthColLength
      ? (windowWidth - totalColWidth + 150 * noWidthColLength) / noWidthColLength - 0.001
      : null;
    // 所有列宽都配置了值
    if (noWidthColLength === 0 && colWidth && index === showColumn.length - 1) {
      return windowWidth - totalColWidth + colWidth;
    }
    return colWidth || averageVal;
  }

  const columnsBase = (listConfigData?.columnList || [])
    .filter((item) => item.cookiesActive && item.isHide === 0)
    .map((item: any, colIndex: number) => {
      const fixedAttr =
        !!item.isColFrozen ||
        colIndex <
          findLastIndex(
            (listConfigData?.columnList || []).filter((v: any) => v.isHide === 0),
            (v: any) => v.isColFrozen,
          )
          ? 'left'
          : false;

      let showMemberLabelColour: MemberLabelColorProps[] = []; // 配置的成员标签颜色
      if ([3, 8].includes(item.valueType) && item.valueTypeMap?.showMemberLabelColourFlag) {
        // 当前列是值列表或维度
        showMemberLabelColour = item.valueTypeMap?.showMemberLabelColour || [];
      }

      return {
        title: () => (
          <Tooltip placement="bottomLeft" arrowPointAtCenter title={item.description?.[locale]}>
            {item.description?.[locale] || item.alias}
          </Tooltip>
        ),
        columnListItem: item,
        dataIndex: item.alias,
        editable: item.isEditable,
        fixed: fixedAttr,
        className: classNames(
          styles[getTableLineHeight(lineHeight)],
          styles.cellBorder,
          styles.otherColumn,
          {
            [styles.textRight]:
              item.valueType === 15 && (item.thousandthSymbol || item.valueTypeMap?.percentage),
            [fixedClassName]: !!fixedAttr,
          },
        ),
        sorter: {
          multiple: 1,
        },
        ellipsis: true,
        width: getColumnWidth(item.customColumnWidth, colIndex),
        render: (text: DataListItemFieldType) => {
          const showText = formatTableShowData({ record: text, cellConfig: item });
          // 优先级最高
          const colStyle = styleObj?.columnStyleObj?.[item.alias]?.[text.value as string];

          // 处理值列表维度成员颜色样式
          let memberLabelStyle = {};
          if (showMemberLabelColour.length) {
            const findLabelColor = showMemberLabelColour.find(
              (it: MemberLabelColorProps) => it.code === text.value,
            );
            // 需要处理显示成员颜色
            if (findLabelColor && findLabelColor.color) {
              memberLabelStyle = {
                padding: '1px 8px',
                borderRadius: 2,
                background: findLabelColor.color as string,
                color: '#ffffff',
                display: 'inline-block',
                overflow: 'hidden',
                maxWidth: '100%',
                lineHeight: '20px',
                textOverflow: 'ellipsis',
              };
            }
          }
          return text?.auth === 'NoAccess' ? (
            'NoAccess'
          ) : (
            <ViewTableCell
              colStyle={colStyle}
              memberLabelStyle={memberLabelStyle}
              showText={showText}
              text={text}
              showMemberLabelColour={showMemberLabelColour}
              align={item?.valueTypeMap?.align}
            />
          );
        },
      };
    });

  React.useEffect(() => {
    form.setFields([
      {
        name: 'listName',
        value: (listConfigData?.dataList || []).map((item) => {
          const newItem = { ...item };
          // MCVJ-6647
          listConfigData?.columnList.forEach((col) => {
            const { alias } = col;
            newItem[alias] = {
              ...newItem[alias],
              value: newItem[alias]?.value === null ? undefined : newItem[alias]?.value,
            };
          });
          return { key: uniqueId(), ...newItem };
        }),
      },
    ]);
  }, [listConfigData]);

  const hasPagination =
    !listConfigData?.baseConfig?.displaySet ||
    (listConfigData?.baseConfig?.displaySet &&
      listConfigData?.baseConfig?.displaySet.includes('PAGER'));

  // 判断 pov 位置那一行的高度
  // ['TITLE', 'FILTER', 'PAGER', 'OPERATION', 'TOOLBAR']
  const getPovPositionHeight = usePersistFn(() => {
    const { povGroupHeight } = getGapByLayout(lineHeight);
    // 如果pov位置上 无pov 并且 工具栏也没有，则高度为0
    const displaySet = listConfigData?.baseConfig?.displaySet || [
      'FILTER',
      'TITLE',
      'PAGER',
      'OPERATION',
      'TOOLBAR',
    ];
    if (
      !displaySet.includes('TOOLBAR') &&
      (!displaySet.includes('FILTER') || (listConfigData?.povList || []).length === 0)
    ) {
      return 0;
    }
    if (displaySet.includes('FILTER') && povHeightInfo?.expand) {
      // 展开状态
      return povHeightInfo?.height;
    }
    return povGroupHeight;
  });

  const paginationHeight = 48; // 分页区域所占高度

  return (
    <Form
      form={form}
      colon={false}
      className={classNames(styles.form, {
        [styles.emptyForm]: !(form.getFieldValue('listName')?.length > 0),
      })}
    >
      <Form.List name="listName">
        {() => {
          return (
            <VirtualStickyTable
              key={showColumn.length}
              scroll={{
                y: size.height
                  ? size.height -
                    getPovPositionHeight() -
                    (lineHeightVal[lineHeight] || 0) -
                    (hasPagination ? paginationHeight : 10)
                  : '100%',
                x: '100%',
              }}
              style={{
                tableLayout: 'auto',
              }}
              pagination={hasPagination ? pagination : false}
              loading={loading}
              onChange={tableChange}
              dataSource={form.getFieldValue('listName')}
              rowKey="key"
              columns={columnsBase as ColumnsType<Record<string, any>>}
              bordered={true}
              height={
                size.height -
                getPovPositionHeight() -
                12 -
                (navigator.userAgent.indexOf('Firefox') && windowWidth < totalColWidth ? 14 : 0) +
                (hasPagination ? 0 : 36)
              }
              itemHeight={lineHeightVal[lineHeight]}
              fixedClassName={fixedClassName}
            />
          );
        }}
      </Form.List>
    </Form>
  );
};

export default FormListTable;
